'''
Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
Date: 2024-08-19 11:55:57
LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
LastEditTime: 2024-08-19 11:56:11
FilePath: \pyplay\wxautoreply.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import pandas as pd
import numpy as np
import pyautogui
import win32gui
import win32con
import time
import logging
from uiautomation import WindowControl

# 设置日志记录
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')


def getHwnd():
    try:
        hwnd = win32gui.FindWindow('WeChatMainWndForPC', '微信')
        win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
        win32gui.SetForegroundWindow(hwnd)
        return hwnd
    except Exception as e:
        logging.error(f"获取窗口句柄时出错: {e}")
        return None


def fuwei(hwnd):
    try:
        if hwnd:
            left, top, right, bottom = win32gui.GetWindowRect(hwnd)
            leftpoint = left + 155
            toppoint = top + 150
            pyautogui.moveTo(leftpoint, toppoint)
            pyautogui.click()
            logging.info('复位操作完成')
        else:
            logging.warning('窗口句柄无效，无法执行复位操作')
    except Exception as e:
        logging.error(f"执行复位时出错: {e}")


def main():
    hwnd = getHwnd()
    if hwnd is None:
        logging.error('无法找到微信窗口，脚本退出')
        return

    wx = WindowControl(Name="微信")
    wx.SwitchToThisWindow()
    hw = wx.ListControl(Name="会话")

    while True:
        try:
            we = hw.TextControl(searchDepth=4)
            if we.Name:
                we.Click(simulateMove=False)
                last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name
                response = '自动回复：无法匹配该关键词~'
                print(last_msg)
                if last_msg == '你好':
                    response = '你好，这条消息是通过autoreply程序进行自动回复！'
                    print(last_msg)
                elif last_msg == '123':
                    response = '你发送了123'
                    print(last_msg)
                elif last_msg == '测试':
                    response = '测试成功'
                    print(last_msg)

                wx.SendKeys(f'{response}' + '{ENTER}')
                fuwei(hwnd)
            time.sleep(1)  # 避免CPU占用过高
        except Exception as e:
            logging.error(f"待机中...: {e}")
            time.sleep(5)  # 发生错误时稍作停顿


if __name__ == "__main__":
    main()
